# 2023-03-25
#python version 3.10
import json
import os
from msvcrt import getwch as m #based on windows platform

def main():
    """选择数据库,表格以及保存,加载内容."""
    global file_flag
    c=m()
    if c=='q':
        return 0
    elif c=='o':
        return 2
    elif c=='s':
        return 3
    elif c=='?':
        return 4
    elif file_flag:
        return c
    return 1

def fda():
    """控制表格"""
    global q,b,t,x,y
    da,ke=q[b][t][:]
    if y<0:
        x,y=x-1,len(ke)-1
    if y>=len(ke):
        x,y=x+1,0
    if x<0:
        x=0
    if x>len(da)-1:
        x=len(da)-1
    out(da,ke,x,y)
    print(f'[{x}-{y}][{q[b][t][0][x][y]}]')
    c=m()
    if c=='0':
        return 0
    elif c=='?':
        help_fda()
    elif 'a'<=c<='z':
        print(c,end='')
        c+=input()
        q[b][t][0][x][y]=c
        y+=1
    elif c=='9':x-=10
    elif c=='3':x+=10
    elif c=='8':x-=1
    elif c=='2':x+=1
    elif c=='4':y-=1
    elif c=='6':y+=1
    elif c=='-' and x!=0:
        q[b][t][0].pop(x)
        x-=1
    elif c=='.':
        i=input('x,y:')
        if len(i.split(','))==2:
            i=i.split(',')
        elif len(i.split(' '))==2:
            i=i.split(' ')
        elif len(i.split('.'))==2:
            i=i.split('.')
        else:
            input('输入出错!')
            return 1
        x,y=map(int,i)
    elif c=='5':
        q[b][t][0][x][y]=input('=')
    elif c=='+':
        q[b][t][0][x][y]+=input('=')
    elif c in('/','*'):
        x,y=len(da),0
        q[b][t][0].append(['*']*len(ke))
        if c=='/':
            for y2 in range(len(ke)):
                c2=input(f'{x}-{y2}=')
                if c2=='':
                    continue
                q[b][t][0][x][y2]=c2
    return 1

def out(da,ke,x,y):
    """格式化输出"""
    os.system("cls||clear")
    print(f'Pg:{x//10:<2}|',end='')
    for k in range(len(ke)):
        print(f'({k}){ke[k]:7}',end='')
    print(end='\n')
    for x2 in range(x-x%10,min(x-x%10+10,len(da))):
        print(f'{str(x2):>5}|',end='')
        for y2 in range(len(ke)):
            if (x2,y2)==(x,y):
                print(f'[{da[x2][y2]:8}]',end='')
            else:
                print(f'{da[x2][y2]:10}',end='')
        print(end='\n')

def fke():
    """控制词头"""
    os.system("cls||clear")
    global q,b,t
    da,ke=q[b][t][:]
    rda=range(len(da))
    lke=len(ke)
    i=0
    for i in zip(range(len(ke)),ke):print(i)
    c=m()
    if c=='q':
        return 0
    elif c=="?":
        help_fke()
    if c in('/','\\','+') and lke<10:
        q[b][t][1].append(input('+'))
        for i in rda:
            q[b][t][0][i].append('*')
    elif c.isdigit() and 0<=int(c)<lke:
        q[b][t][1][int(c)]=input(str(ke[int(c)])+'->')
    elif c=='-':
        print('pop=')
        c2=m()
        if c2.isdigit() and 0<int(c2)<lke:
            print(f"`{q[b][t][1][int(c2)]}`")
            q[b][t][1].pop(int(c2))
            for i2 in rda:
                q[b][t][0][i2].pop(int(c2))
    return 1

def help_main():
    print(
"""欢迎来到表格程序!
\033[1;36;40m
本软件可以自由复制修改分享!
邮箱:youngasusual@qq.com
\033[0m
直接输入:
o 打开文档
b 打开数据库
x 删除数据库
t 打开表格
d 删除表格
s 保存并退出文档
q 退出
按任意键继续...""")
    m()

def help_fda():
    print(
"""说明书:
/=新行并修改 *=新行 -=删除行
       8=上   9=上页
4=左 5=修改  6=右 +=添加
       2=下 3=下页
0=退出 .=跳转
按任意键继续..."""
    )
    m()

def help_fke():
    print(
"""说明书:
输入0-9的数重命名那个表头
输入-然后0-9删除那个表头
输入/或+添加表头
输入q退出
按任意键继续..."""
    )
    m()


q:dict={}
file:str="unknow"
file_flag:bool=False
b:str="unknow"
t:str="unknow"
file_content={True:"已打开,未s保存",False:"已关闭,需要按o打开"}
help_main()
while True:
    os.system("cls||clear")
    admit=b in q and t in q[b]
    print("?帮助 q退出")
    print(f"o文档 {file} {file_content[file_flag]}")
    if file_flag:
        print("b数据库(x 删除):")
        for ib in q.keys():
            if ib==b:
                print('<',ib,'>',end="  ")
            else:
                print(ib,end="  ")
        print("\nt表格(d 删除):")
        if b in q:
            for it in q[b].keys(): # type: ignore
                if it==t:
                    print('<',it,'>',end="  ")
                else:
                    print(it,end="  ")
        if admit:
            print(
"""
现在输入 空格 可以进入表格了!
输入 k 修改表头"""
            )
        else:
            print(
"""请选择数据库和表格"""
            )
    fla=main()
    if fla==0:#quit
        break
    elif fla==2:#open
        os.system("cls||clear")
        print("路径:",os.getcwd(),"\n你的文件:")
        for i in os.listdir():
            if os.path.isfile(i):
                print(i)
        file=input("输入要打开的文档:")
        if os.path.isfile(file):
            with open(file,"r") as book:
                q=json.loads(book.read())
            if "root" in q and q["root"]=="TableEdit":
                q.pop("root")
                file_flag=True
            else:
                input("不是正确的格式")
                file="unknow"
                file_flag=False
                b,t="unknow","unknow"
        else:
            open(file,"w").close()
            input("该文件不存在,已创建")
            file_flag=True
            q={"base":{"table":[[["*"]],["*"]]}}
    elif fla==3 and file_flag:#save
        with open(file,"w+") as book:
            flag_cover=input("是否覆盖?[y是/n否]")
            if flag_cover=="y":
                q.setdefault("root","TableEdit") # type: ignore
                book.write(json.dumps(q))
                file_flag=False
    elif fla==4:#help
        help_main()
    elif fla in ("b","x","t","d"," ","k"):
            if fla=='b':
                b=input("输入数据库:")
                q.setdefault(b,{})
                t="unknow"
            elif fla=='x':#删除base
                for i in zip(range(len(q.keys())),q.keys()):
                    print(i)
                del_b=input("输入数字删除:")
                if '0'<=del_b<str(len(q)):
                    q.pop(list(q.keys())[int(del_b)])
            elif b in q and fla=='t':
                t=input("输入表格:")
                q[b].setdefault(t,[[['*']],['*']])
            elif b in q and fla=='d':#删除table
                for i in zip(range(len(q[b].keys())),q[b].keys()):
                    print(i)
                del_t=input("输入数字删除:")
                if '0'<=del_t<str(len(q[b])):
                    q[b].pop(list(q[b].keys())[int(del_t)])
            if admit:
                if fla==' ':
                    help_fda()
                    x,y=0,0
                    while fda():pass
                elif fla=='k':
                    help_fke()
                    while fke():pass